#include <stdio.h>
#include "util.h"
#include "log.h"
#include "cjson.h"
#include "config.h"

int GetConfigValue(const char *profile, char *tile, char *key, char *value)
{
    LOG(CFG_LOG_MODULE, CFG_LOG_PROC, "GetConfigValue\n");
    if (profile == NULL || tile == NULL || key == NULL || value == NULL)
        return -1;

    int ret = 0;
    char *buffer = NULL;
    FILE *fp = NULL;

    do
    {
        fp = fopen(profile, "r");
        if (fp == NULL)
        {
            ret = -1;
            break;
        }

        // 将文件指针移动到文件末尾
        fseek(fp, 0, SEEK_END);
        // 获取文件长度
        int len = ftell(fp);
        // 将文件指针移动到文件开头
        fseek(fp, 0, SEEK_SET);

        buffer = (char *)MALLOC(len + 1);
        memset(buffer, 0, len + 1);

        fread(buffer, 1, len, fp);

        cJSON *json = cJSON_Parse(buffer);
        if (json == NULL)
        {
            LOG(CFG_LOG_MODULE, CFG_LOG_PROC, "parse json error\n");
            ret = -1;
            break;
        }

        cJSON *jsonTitle = cJSON_GetObjectItem(json, tile);
        if (jsonTitle == NULL)
        {
            LOG(CFG_LOG_MODULE, CFG_LOG_PROC, "get json title error\n");
            ret = -1;
            break;
        }

        cJSON *jsonKey = cJSON_GetObjectItem(jsonTitle, key);
        if (jsonKey == NULL)
        {
            LOG(CFG_LOG_MODULE, CFG_LOG_PROC, "get json key error\n");
            ret = -1;
            break;
        }

        strcpy(value, jsonKey->valuestring);
        cJSON_Delete(json);
        break;

    } while (0);

    if (fp != NULL)
        fclose(fp);
    if (buffer != NULL)
        FREE(buffer);

    return ret;
}

int GetMysqlInfo(char *user, char *pwd, char *db)
{
    LOG(CFG_LOG_MODULE, CFG_LOG_PROC, "GetMysqlInfo\n");
    if (user == NULL || pwd == NULL || db == NULL)
        return -1;

    int ret = 0;

    do
    {
        ret = GetConfigValue(CONFIG_PATH, "mysql", "user", user);
        if (ret != 0)
        {
            LOG(CFG_LOG_MODULE, CFG_LOG_PROC, "get mysql user error\n");
            ret = -1;
            break;
        }

        ret = GetConfigValue(CONFIG_PATH, "mysql", "password", pwd);
        if (ret != 0)
        {
            LOG(CFG_LOG_MODULE, CFG_LOG_PROC, "get mysql password error\n");
            ret = -1;
            break;
        }

        ret = GetConfigValue(CONFIG_PATH, "mysql", "database", db);
        if (ret != 0)
        {
            LOG(CFG_LOG_MODULE, CFG_LOG_PROC, "get mysql database error\n");
            ret = -1;
            break;
        }

    } while (0);

    return ret;
}
